<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Product\ProductMaterial;
use App\Models\Product\ProductMaterialApply;
use App\Util\RExcel;
use App\Util\SerialNo;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Illuminate\Support\Facades\Request;

class MaterialApplyController extends AdminController{

    protected $title = '物料申请';

    protected function grid()
    {
        $grid = new Grid(new ProductMaterialApply());
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('apply_no','申请单号');
        $grid->column('title','申请材料名称');
        $grid->column('spec','规格');
        $grid->column('craft','工艺');
        $grid->column('function','功能性');
        $grid->column('color','颜色');
        $grid->column('cylce','寻源周期(截止日期)');
        $grid->column('quote_price','报价');
        $grid->column('quote_currency','报价单位');
        $grid->column('admin_id','申请人')->display(function ($value){
            return $value ? User::getUsernameById($value) : '';
        });
       $grid->column('audit_status','审核状态')->using(ProductMaterial::$_auditStatus);
        $grid->column('audit_admin_id','审核人')->display(function ($value){
            return $value ? User::getUsernameById($value) : '';
        });
        $grid->column('audit_time','审核日期');
        $grid->column('audit_remark','审核备注');
        $grid->column('origin_status','寻源结果')->using(ProductMaterial::$_originStatus);
        $grid->column('origin_time','寻源时间');
        $grid->column('origin_remark','寻源备注');
        $grid->column('material_code','在库材料编码');
        $grid->column('status','是否入库')->bool([ProductMaterial::STATUS_YES => true, ProductMaterial::STATUS_NO => false]);
        $grid->column('操作')->view('products.material-apply.action');

        $grid->disableActions();
        $grid->fixHeader();
        $grid->fixColumns(0,0);
        $grid->paginate(10);
        $grid->disableExport();
        $grid->disableBatchActions();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('products/material-apply-download'));
        });

        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter){
                $filter->where(function ($query) {
                    $query->where('material_code', 'like', "%{$this->input}%");
                }, '查询','sku8')->placeholder('模糊查询材料编码');
                $filter->in('audit_status', '审核状态')->checkbox(ProductMaterial::$_auditStatus);
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('material_id', '在库材料')->select(ProductMaterial::options());
                $filter->equal('audit_admin_id','审核人')->select(User::getMUserOptions());
            });
        });
        return $grid;
    }

    protected function form(){
        $form = new Form(new ProductMaterialApply());
        $form->hidden('id');

        if ($form->isCreating()) {
            $form->hidden('apply_no');
            $form->hidden('status','是否入库')->default(ProductMaterial::IN_NO);
            $form->hidden('origin_status','寻源结果')->default(ProductMaterial::ORIGIN_IN);
            $form->hidden('audit_status','审核状态')->default(ProductMaterial::AUDIT_NO);
            $form->hidden('admin_id')->default(Admin::user()->id); //申请人
        }
        $form->text('title','申请材料名称')->rules('required')->help('申请材料名称规则：材质+规格+工艺(功能)');
        $form->text('spec','规格');
        $form->text('craft','工艺');
        $form->text('function','功能性');
        $form->text('color','颜色');
        $form->date('cylce','寻料周期')->required()->help('请确认申请材料的交货日期(截止时间)')->width(5);
        $form->decimal('quote_price','需求数量');
        $form->select('quote_currency','需求单位')->options(ProductMaterial::$_quote_currency);
        $form->textarea('apply_remark','申请备注');
        $form->hidden('apply_month')->default(date('Y-m'));


        $form->saving(function (Form $form) {
            if ($form->isCreating()) {
                //添加申请单号
                $applyNo = SerialNo::getMaterialApplyNo();
                $apply = ProductMaterialApply::query()->where('apply_no',$applyNo)->first();
                if ($apply) {
                    admin_error('ERROR', '该材料申请单号已存在, 请重新尝试');
                    return back()->withInput();
                }
                $form->apply_no = $applyNo;
            }
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        return $form;
    }


    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProductMaterialApply::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->where(function ($query) use($_filter){
                    $query->where('material_code', 'like', "%{$_filter}%");
                });
            }
            if(in_array($key,['audit_status', 'material_id', 'audit_admin_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['申请单号','在库材料编码','申请材料名称','规格','工艺','功能性','颜色','寻源周期(截止日期)','报价','报价单位',
            '申请人','申请描述','寻源结果','寻源备注','是否入库','审核状态','审核人','审核日期','审核备注'];
        RExcel::exportCsv('材料申请单',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        foreach ($res as $model){
            $temp = [
                $model->apply_no ?? '',
                $model->material_code ?? '',
                $model->title ?? '',
                $model->spec ?? '',
                $model->craft ?? '',
                $model->function ?? '',
                $model->color ?? '',
                $model->cylce ?: '',
                $model->quote_price ?? '',
                $model->quote_currency ? ProductMaterial::$_quote_currency[$model->quote_currency] : '',
                $model->admin_id ? User::getUsernameById($model->admin_id) : '',
                $model->apply_remark ?? '',
                $model->origin_status ? ProductMaterial::$_originStatus[$model->origin_status] : '',
                $model->origin_remark ?? '',
                $model->status ? ProductMaterial::$_status[$model->status] : '',
                $model->audit_status ? ProductMaterial::$_auditStatus[$model->audit_status] : '',
                $model->audit_admin_id ? User::getUsernameById($model->audit_admin_id) : '',
                $model->audit_time ?: '',
                $model->audit_remark ?? '',
            ];
            yield $temp;
        }
    }

}
